package com.studynotes.dev.tech.common.utils;

import cn.hutool.extra.spring.SpringUtil;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.support.RequestContextUtils;

import java.util.Locale;
import java.util.Objects;

/**
 * @author Liu XiaoJun
 * @description: I18n Message Utils
 * @date 2025-11-07 13:38:19
 */
public class I18nMessageUtil {

    private static final MessageSource messageSource;

    private I18nMessageUtil() {
        throw new IllegalStateException("Utility class");
    }

    static {
        messageSource = SpringUtil.getBean(MessageSource.class);
    }

    public static String getMessage(String code) {
        return getMessage(code, new Object[]{});
    }

    public static String getMessage(String code, String defaultMessage) {
        return getMessage(code,  new Object[]{}, defaultMessage);
    }

    public static String getMessage(String code, String defaultMessage, Locale locale) {
        return getMessage(code,  new Object[]{}, defaultMessage, locale);
    }

    public static String getMessage(String code, Locale locale) {
        return getMessage(code,  new Object[]{}, "", locale);
    }

    public static String getMessage(String code, Object[] args) {
        return getMessage(code, args, "");
    }

    public static String getMessage(String code, Object[] args, Locale locale) {
        return getMessage(code, args, "", locale);
    }

    public static String getMessage(String code, Object[] args, String defaultMessage) {
        Locale locale;
        if (ServletUtil.isRequest()) {
            locale = RequestContextUtils.getLocale(Objects.requireNonNull(ServletUtil.getRequest()));
        } else {
            locale = LocaleContextHolder.getLocale();
        }
        return getMessage(code, args, defaultMessage, locale);
    }

    public static String getMessage(String code, Object[] args, String defaultMessage, Locale locale) {
        return messageSource.getMessage(code, args, defaultMessage, locale);
    }

}
